package erik.util;

import java.util.NoSuchElementException;

public class Collections
{
    private Collections( )
    {
    }
    
    /**
     * Returns the maximum object in the collection, using default ordering
     * @param coll the collection.
     * @return the maximum object.
     * @throws NoSuchElementException if coll is empty.
     * @throws ClassCastException if objects in collection cannot be compared.
     */
    public static <T extends Object & Comparable<? super T>>
    T max(Collection<? extends T> coll)
    {
        return max( coll, new DefaultComparator<T>( ) );
    }
    
    /**
     * Returns the maximum object in the collection, using comparator.
     * @param coll the collection.
     * @param cmp the comparator.
     * @return the maximum object.
     * @throws NoSuchElementException if coll is empty.
     * @throws ClassCastException if objects in collection cannot be compared.
     */
    public static <T>
    T max(Collection<? extends T> coll, Comparator<? super T> cmp)
    {
        if( coll.size( ) == 0 )
            throw new NoSuchElementException( );
            
			
		Iterator<? extends T> itr = coll.iterator( );
        T maxValue = itr.next( );
        
        while( itr.hasNext( ) );
        {
			T current = itr.next( );
            if( cmp.compare( current, maxValue ) > 0 )
                maxValue = current;
        }
        
        return maxValue;    
    }
    
    
    /*
     * Returns a comparator that imposes the reverse of the
     * default ordering on a collection of objects that
     * implement the Comparable interface.
     * @return the comparator.
     */
    public static <T> Comparator<T> reverseOrder( )
    {
        return new ReverseComparator<T>( );
    }
    
    private static class ReverseComparator<T> implements Comparator<T>
    {
        public int compare( T lhs, T rhs )
        {                
            return - ((Comparable)lhs).compareTo( rhs );
        }
    }
        
    
    static class DefaultComparator<T extends Comparable<? super T>> implements Comparator<T>
    {
        public int compare( T lhs, T rhs )
        {                
            return lhs.compareTo( rhs );
        }
    }
}

